package com.sugon.modules.utils;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * HTTP工具类
 *
 * @author YuXD
 * @since 2021-12-15
 */
public class HttpUtil {

    /**
     * 从请求对象中获取完整的请求路径，包括参数
     *
     * @param request 基于HTTP协议的请求对象
     * @return
     */
    public static final String getRequestPath(HttpServletRequest request) {
        StringBuffer requestPath = request.getRequestURL();
        if (requestPath.indexOf("?") < 0) {
            // 处理查询字符串
            String queryString = request.getQueryString();
            if (StrUtil.isNotEmpty(queryString)) {
                requestPath.append("?").append(queryString);
            }
        }
        return requestPath.toString();
    }

    /**
     * 根据参数MAP构建查询参数
     * {'key1':'value1','key2':'value2'} -> ?key1=value1&key2=value2
     *
     * @param paramMap 基于HTTP协议的请求对象
     * @return
     */
    public static final String buildQueryParam(Map<String, String> paramMap) {
        StringBuffer requestPath = new StringBuffer();
        List<String> tem = CollectionUtil.newArrayList();
        String queryParamTemplate = "{}={}";
        paramMap.forEach((key, value) -> {
            if (StrUtil.isNotEmpty(value)) {
                tem.add(StrUtil.format(queryParamTemplate, key, value));
            }
        });
        String queryParam = CollectionUtil.join(tem, "&");
        return StrUtil.isNotEmpty(queryParam) ? "?" + queryParam : "";
    }

}
